import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpHeaderResponse, HttpInterceptor, HttpProgressEvent, HttpRequest, HttpResponse, HttpSentEvent, HttpUserEvent } from '@angular/common/http';
import { Observable, Subject, throwError, timeout } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd/message';
import { catchError, delay, takeUntil, tap } from 'rxjs/operators';
import { ConfigModule } from '../config.module';
import { environment } from '../../environments/environment';
import { Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { WebStorageService } from './webStorage.service';

/**
 * 拦截器
 */
@Injectable({
    providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
    pendingHttpRequests$: Subject<any> = new Subject<void>();
    authHeaderProperty = 'Authorization';
    isConfirmShown: boolean;
    constructor(
        private _nzMessageService: NzMessageService,
        private _config: ConfigModule,
        private _router: Router,
        private _nzModalService: NzModalService,
        private webStorageService: WebStorageService
    ) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        //获取token
        const authToken = localStorage.getItem('token');

        // 统一加上服务端前缀
        let url = req.url;
        const host = this.webStorageService.getHost();
        if (host!=null){
            url = url.replace(environment.baseUrl, host);
        }
        let authReq = req.clone({
            url,
            headers: req.headers.set('clientid', environment.clientId)
        });

        const method = req.method.toLowerCase();


        // 检查是否需要添加 token
        if (authToken !== null ){
            authReq =  authReq.clone({
                url: authReq.url,
                headers: req.headers.set(this.authHeaderProperty, 'Bearer '+authToken)
                    .set('clientid', environment.clientId)
            });
        }

        return next.handle(authReq).pipe(
            delay(200),
            takeUntil(this.pendingHttpRequests$.asObservable()),
            timeout(60000),
            tap(
                (event) => {
                    this.webCodeOption(authReq.url, event);
                    // this.apmsCodeOption(authReq.url, event);
                },
                (error) => {
                    // this.errorOption(error);
                }
            ),
            catchError((error) => {
                if (error instanceof ErrorEvent) {
                    // 客户端错误
                    this._nzMessageService.create('error', '客户端错误: ' + error.message);
                } else if (error.name === 'TimeoutError') {
                    // 超时错误
                    this._nzMessageService.create('error', '请求超时，请检查网络连接或稍后再试！');
                } else {
                    // 服务器错误
                    this.errorOption(error);
                }
                return throwError(error);
            })
        );
    }

    webCodeOption(url: string, event: HttpSentEvent | HttpHeaderResponse | HttpResponse<any> | HttpProgressEvent | HttpUserEvent<any>){
        if (url.startsWith(environment.baseUrl)){
            if (event instanceof HttpResponse) {
                if (event.body.code === 401) {
                    // this.pendingHttpRequests$.next();
                    if (!this.isConfirmShown){
                        this._nzModalService.confirm({
                            nzTitle: '<i>温馨提示</i>',
                            nzContent: `<b>登录凭证已过期，点击确定重新登录！</b>`,
                            nzCancelText: null,
                            nzCloseIcon: null,
                            nzWrapClassName: 'vertical-center-modal',
                            nzOnOk: () => {
                                localStorage.clear();
                                this.isConfirmShown = false;
                                this._router.navigateByUrl('/login').finally();
                            }
                        });
                        this.isConfirmShown = true;
                    }
                } else if (event.body.code === 401) {
                    localStorage.clear();
                    this._router.navigateByUrl('/login');
                }
                else if (event.body.code !== 200 && event.body.msg !== undefined) {
                    this._nzMessageService.create('error', event.body.msg);
                }

                if (event.body.code === 200){
                    //统一加上判断值
                    event.body.success = true;
                }
            }
        }
    }

    /**
     * 请求错误返回值处理
     * @param error
     */
    errorOption(error: any){
        switch (error.status) {
            case 500:
                this._nzMessageService.create('error', '请求失败，请重试！');
                break;
            case 405:
                this._nzMessageService.create('error', '请求方法错误！');
                break;
            case 400:
                this._nzMessageService.create('error', 'Bad Request！');
                break;
            case 404:
                this._nzMessageService.create('error', `找不到接口：${error.error.path}！`);
                break;
            default:
                this._nzMessageService.create('error', error.statusText);
        }
    }
}
